package com.tchepannou.limbe.validation;

import com.tchepannou.util.converter.DoubleConverter;

import javax.validation.constraints.DecimalMin;
import java.lang.reflect.Field;

/**
 * User: herve
 * Date: 14-01-12 12:03 PM
 */
public class DecimalMinValidator extends AbstractValidator
{
    protected DoubleConverter _converter = new DoubleConverter();

    @Override
    public boolean validate(Object bean, Field field)
    {
        Double min = getMin(field);
        if (min == null)
        {
            return true;
        }

        Object value = getValue(bean, field);
        if (value == null)
        {
            return true;
        }
        else if (Number.class.isAssignableFrom(value.getClass()))
        {
            return ((Number)value).doubleValue() >= min.doubleValue();
        }
        else if (value instanceof String)
        {
            Double xvalue = (Double)_converter.convert(value);
            return xvalue.doubleValue() >= min.doubleValue();
        }
        else
        {
            return false;
        }
    }

    @Override
    public boolean validate(Object bean)
    {
        return false;
    }

    protected Double getMin (Field field)
    {
        DecimalMin anno = field.getAnnotation(DecimalMin.class);
        if (anno == null)
        {
            return null;
        }

        return (Double)_converter.convert(anno.value());
    }
}
